import java.util.Arrays;
import java.util.Stack;
//取出数组中至字典序最小的k个元素
public class smallestarray {
    public static void main(String[] args) {
        int[] a = {10,5,4,11,6,17,8};
        int k =3;
        int[] ans = findsmallSeq(a,k);
        System.out.println("最后的结果是"+ Arrays.toString(ans));
    }
    private static int[] findsmallSeq(int[] a, int k){
        int[] ans = new int[k];
        Stack<Integer> s = new Stack<>();
        for(int i=0;i<a.length;i++){
            final int x = a[i];
            final int left = a.length-i;
            while(!s.empty()&&(s.size()+left>k)&&s.peek()>x){
                s.pop();
            }
            s.push(x);
        }


        while(s.size()>k){
            s.pop();
        }

        for(int i=k-1;i>=0;i--){
            ans[i] = s.peek();
            s.pop();
        }
        return ans;
    }
}
